from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import Optional, Dict, Any

from quantcore.db import Mongo


@dataclass
class PositionService:
    strategy_id: str = "alpha1"

    def get(self, symbol: str) -> Optional[Dict[str, Any]]:
        col = Mongo.col("positions")
        return col.find_one({"_id.strategy_id": self.strategy_id, "_id.symbol": symbol})

    def upsert(self, symbol: str, qty: int, cost_price: float, last_price: float) -> None:
        col = Mongo.col("positions")
        col.update_one(
            {"_id": {"strategy_id": self.strategy_id, "symbol": symbol}},
            {
                "$set": {
                    "qty": qty,
                    "cost_price": cost_price,
                    "last_price": last_price,
                    "market_value": last_price * qty,
                    "pnl_pct": (last_price - cost_price) / cost_price if cost_price else 0.0,
                    "update_time": datetime.utcnow(),
                }
            },
            upsert=True,
        )




